<?php
/**
 * admin端素材库
 */
namespace App\Http\Controllers;

use App\Models\Attachment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Kuyuan\Phpwidget\File;

class AttachmentController extends Controller
{
    /**
     * 上传素材
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function upload(Request $request)
    {
        $File = $request->file('file');
        $_absolute_path = $File->store(File::stringDir('images'));
        $_setting = $this->getConfig();
        $Attachment = Attachment::create(array(
            'uid' => auth()->id(),
            'filename' => $File->getClientOriginalName(),
            'attachment' => $_absolute_path,
            'storage_type' => 'default'
        ));
        // 是否开启了远程附件
        if($_setting['media']['storage'] != 'default') {
            if(cool_upload_remote($_absolute_path)) {
                $Attachment->storage_type = $_setting['media']['storage'];
                $Attachment->save();
            }
        }
        return response([
            'data' => $Attachment
        ]);
    }

    /**
     * 获取附件列表
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function getList(Request $request)
    {
        $Attachment = Attachment::where('type',$request->type)
            ->orderBy('id','desc')
            ->offset($request->limit[0])
            ->limit($request->limit[1])
            ->get();
        return response([
            "data"=>$Attachment
        ]);
    }

    /**
     * 获取系统附件url链接
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function getAttachmentUrl(Request $request)
    {
        $Attachment = Attachment::where('attachment',$request->input('attachment'))->first();
        return response([
            "data" => $Attachment->url
        ]);
    }

    /**
     * 删除素材附件
     * @param int $_attachment_id 附件素材id
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function delete($_attachment_id)
    {
        DB::beginTransaction();
        try{
            $Attachment = Attachment::find($_attachment_id);
            // 删除远程附件
            if($Attachment->storage_type != 'default') {
                cool_delete_remote($Attachment->attachment,$Attachment->storage_type);
            } else {
                @unlink(storage_path('app/public/'.$Attachment->attachment));
            }
            $Attachment->delete();
            DB::commit();
            return response('删除成功');
        }catch (\PDOException $e) {
            DB::rollBack();
            return response('删除失败', 401);
        }
    }
}
